<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="导入助手" @ok="handleSubmit" width="550px" destroyOnClose>
    <div v-html="topRef"></div>
    <template #footer>
      <Button @click="handleClose">取消</Button>
      <Button 
        type="primary" 
        v-if="templateUrl" 
        class="button-color-green" 
        @click="handleDownloadTemplate"
      >
        下载模板
      </Button>
      <a-upload name="file" 
        class="ant-btn"
        :showUploadList="false" 
        :customRequest="(file) => handleImportRequest(file)"
      >
        <Button type="primary">导入</Button>
      </a-upload>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { Button } from 'ant-design-vue'
import { getArticle } from '/@/api/sys/article'
import { downloadByRequestUrl } from '/@/utils/file/download';

const emit = defineEmits(['register', 'success']);

const templateFileName = ref()
const templateUrl = ref()
const props = defineProps({
  importRequest: {
    type: Function as PropType<(arg?: any, successCallback?: Function) => any>,
    default: null,
  },
});

const topRef = ref('暂无提示')
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ confirmLoading: false })
  const { tipArticleCode, name } = data
  templateFileName.value = name
  if (tipArticleCode) {
    try {
      setModalProps({ 
        confirmLoading: false, 
        loading: true,
        canFullscreen: false,
        draggable: false
      })
      const { content, attachments } = await getArticle({ code: tipArticleCode, isFormSceneTenant: true })
      topRef.value = content
      templateUrl.value = attachments && attachments.length > 0 ? attachments[0].url : undefined
    } finally {
      setModalProps({ loading: false })
    }
  }
});

const handleClose = () => {
  closeModal();
}

const handleImportRequest = (file) => {
  closeModal();
  props.importRequest && props.importRequest(file)
}

const handleDownloadTemplate = () => downloadByRequestUrl({
 url: templateUrl.value, 
 fileName: templateFileName.value 
})

const handleSubmit = (v) => {
  try {
    
    closeModal();
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped>

</style>
